//1. 引入fs模块  
const { json } = require('express');
const fs = require('fs');

// 获取类型
let stat = (filename) => {
  return new Promise((res, rej) => {
    // 调用fs.stat方法，传入文件，通过回调函数处理data对象  
    fs.stat(filename, (err, data) => {
      if (err) {
        console.log('err -----');
        console.log(err);
        rej(err)
        return
      }

      //3. 调用 isFile()方法判断是否为文件  
      console.log(`is file: ${data.isFile()}`)
      //4. 调用 isDirectory()方法判断是否为目录  
      console.log(`is directory: ${data.isDirectory()}`)

      let str = ""
      if (data.isDirectory()) {
        str = "目录"
      } else if (data.isFile()) {
        str = "文件"
      } else {
        str = "什么也不是"
      }

      res(str)
    })
  })
}

// 写
let write = (path, text) => {
  return new Promise((res, rej) => {
    // res("path:" + path)
    fs.writeFile(path, text, error => {
      // console.log('开始写入:' + text);
      if (error) {
        console.log('write err');
        console.log(error);
        res(false)
      } else {
        console.log("写入成功");
        res(true)
      }
    });
  })
}

// 追加
let append = (path, text) => {
  return new Promise((res, rej) => {
    // res("path:" + path)
    fs.appendFile(path, text, error => {
      // console.log('开始 fs');
      if (error) {
        console.log("追加失败");
        res(false)
      } else {
        console.log("追加成功");
        res(true)
      }
    });
  })
}

// 读
let read = (path) => {
  return new Promise((res, rej) => {
    // res("path:" + path)
    fs.readFile(path, "utf-8", function (error, data) {
      // console.log(error);  //如果err为null就说明读取成功了,没有出错
      // console.log(data); // 如果不给第二个参数[读取的文件编码格式]就会以beffer格式输出

      //  用error来判断文件是否读取成功
      if (error) {
        console.log('error');
        res(false)
      } else {
        res(data)
      }
      // console.log("读取文件成功,内容是" + data);

    });
  })
}

// 读取文件夹下所有文件
let readDir = (pathName) => {
  return new Promise((res, rej) => {
    // res("path:" + path)
    fs.readdir(pathName, function (err, files) {
      var dirs = [];
      if (err) {
        rej(err)
      } else {
        res(files)
      }
    })
  })
}

// 获取所有子文件夹
let getAllDirOnly = (pathName) => {
  return new Promise((res, rej) => {
    // res("path:" + path)
    let allDir = []
    const files = fs.readdirSync(pathName)
    files.forEach(function (item, index) {
      // console.log(item);
      let stat = fs.lstatSync(pathName + item)
      if (stat.isDirectory() === true) {
        allDir.push(item)
      }
    })
    // console.log('all dir');
    // console.log(allDir);
    res(allDir)
  })
}

// 专用
let getInfo = (pathName, dirName) => {
  console.log('pathName:' + pathName);
  const files = fs.readdirSync(pathName)

  let json
  let flag = false

  files.forEach(function (item, index) {

    // let stat = fs.lstatSync(pathName + item)

    if (item == 'info.json') {
      json = fs.readFileSync((pathName + item), 'UTF-8')
      json = JSON.parse(json)
      json.path = pathName
      json.dirName = dirName
      // console.log(json);
      flag = true
    }
  })


  if (flag) {
    return json
  } else {
    return {
      "name": null,
      "versions": null,
      "edit": false,
      path: null
    }
  }
}

// 设置
let setInfo = (pathName, fileInfo) => {
  console.log('setInfo:' + pathName);
  const files = fs.readdirSync(pathName)
  
  let json
  let flag = false
  let arr = []

  files.forEach(async function (item, index) {

    // let stat = fs.lstatSync(pathName + item)

    if (item == 'info.json') {
      console.log('找到 info json ----1');
      json = fs.readFileSync((pathName + item), 'UTF-8')
      console.log('找到 info json ----2');
      json = JSON.parse(json)
      json.versions.unshift(fileInfo)
      // console.log(json.versions);
      let str = JSON.stringify(json)
      // try {
      //   console.log('写入'+(pathName + item)+'done');
      //   fs.writeFileSync((pathName + item), str);
      // } catch (error) {
      //   console.log('写入'+(pathName + item)+'出错');
      // }
      let ret = await write((pathName + item),str)
      console.log('找到 info json ----3');
      arr = json.versions
    }
  })
  console.log('set info, versions success');
  return arr
}

// 清空设置
let emptyInfo = async (pathName, info) => {
  console.log('emptyInfo:' + pathName);

  delDir(pathName)

  let json = JSON.stringify(info)
  
  let ret = await write((pathName + 'info.json'),json)

  console.log('reset info, versions success');
  return ret
}

// 删除文件夹下文件
let delDir = (path) => {
  let files = [];
  if(fs.existsSync(path)){
      files = fs.readdirSync(path);
      files.forEach((file, index) => {
          let curPath = path + "/" + file;
          if(fs.statSync(curPath).isDirectory()){
              delDir(curPath); //递归删除文件夹
          } else {
              fs.unlinkSync(curPath); //删除文件
          }
      });
  }
}


module.exports.stat = stat
module.exports.write = write
module.exports.append = append
module.exports.read = read
module.exports.readDir = readDir
module.exports.getAllDirOnly = getAllDirOnly
module.exports.getInfo = getInfo
module.exports.setInfo = setInfo
module.exports.emptyInfo = emptyInfo
module.exports.delDir = delDir


